<?php
session_start();
if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] != 1) {
    header('Location: login.php');
    exit;
}

// 数据库配置
$host = 'localhost';
$dbname = 'itops_help1_center';
$username = 'itops_help1_center';
$password = 'itops_help1_center';

$error = '';

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');
    $confirmPwd = trim($_POST['confirm_password'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $isAdmin = (int)($_POST['is_admin'] ?? 0);
    $status = (int)($_POST['status'] ?? 1);

    // 验证
    if (empty($username)) {
        $error = "用户名不能为空";
    } elseif (strlen($username) < 3 || strlen($username) > 20) {
        $error = "用户名长度必须在3-20个字符之间";
    } elseif (empty($password)) {
        $error = "密码不能为空";
    } elseif (strlen($password) < 6) {
        $error = "密码长度不能少于6个字符";
    } elseif ($password != $confirmPwd) {
        $error = "两次输入的密码不一致";
    } elseif (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "邮箱格式不正确";
    } else {
        try {
            $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
            
            // 检查用户名是否存在
            $stmt = $pdo->prepare("SELECT id FROM user WHERE username = :username");
            $stmt->execute([':username' => $username]);
            if ($stmt->fetch()) {
                $error = "该用户名已存在，请更换";
                return;
            }

            // 插入用户（密码加密存储）
            $hashedPwd = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO user 
                                (username, password, email, is_admin, status, register_time)
                                VALUES (:username, :password, :email, :admin, :status, NOW())");
            $stmt->execute([
                ':username' => $username,
                ':password' => $hashedPwd,
                ':email' => $email,
                ':admin' => $isAdmin,
                ':status' => $status
            ]);

            header('Location: user.php?success=用户添加成功');
            exit;
        } catch (PDOException $e) {
            $error = "添加失败：" . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新增用户 - IT知识库管理系统</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="css/common.css">
</head>
<body>
    <div class="admin-container">
        <!-- 统一侧边栏 -->
        <aside class="admin-sidebar">
            <div class="sidebar-header">
                <div class="sidebar-logo">
                    <i class="fas fa-cogs"></i>
                    <span>知识库管理</span>
                </div>
            </div>
            <ul class="nav-list">
                <li class="nav-item">
                    <a href="index.php" class="nav-link">
                        <i class="fas fa-home"></i>
                        <span>管理首页</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="article.php" class="nav-link">
                        <i class="fas fa-file-alt"></i>
                        <span>文章管理</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="category.php" class="nav-link">
                        <i class="fas fa-folder"></i>
                        <span>分类管理</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="version.php" class="nav-link">
                        <i class="fas fa-sync-alt"></i>
                        <span>版本管理</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="user.php" class="nav-link active">
                        <i class="fas fa-users"></i>
                        <span>用户管理</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="logout.php" class="nav-link">
                        <i class="fas fa-sign-out-alt"></i>
                        <span>退出登录</span>
                    </a>
                </li>
            </ul>
        </aside>

        <!-- 内容区 -->
        <main class="admin-content">
            <div class="content-wrapper">
                <div class="page-header">
                    <h1 class="page-title">新增用户</h1>
                    <a href="user.php" class="btn btn-outline">
                        <i class="fas fa-arrow-left"></i>返回列表
                    </a>
                </div>

                <?php if ($error): ?>
                    <div class="message message-error">
                        <i class="fas fa-exclamation-circle"></i>
                        <span><?php echo $error; ?></span>
                    </div>
                <?php endif; ?>

                <div class="form-card">
                    <form method="post" action="user_add.php">
                        <div class="form-group">
                            <label class="form-label" for="username">
                                用户名 <span class="required">*</span>
                            </label>
                            <input type="text" id="username" name="username" class="form-control" 
                                placeholder="3-20个字符" 
                                value="<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>">
                            <div class="form-hint">用户名由字母、数字或下划线组成，长度3-20字符</div>
                        </div>

                        <div class="form-group">
                            <label class="form-label" for="password">
                                密码 <span class="required">*</span>
                            </label>
                            <input type="password" id="password" name="password" class="form-control" 
                                placeholder="至少6个字符">
                        </div>

                        <div class="form-group">
                            <label class="form-label" for="confirm_password">
                                确认密码 <span class="required">*</span>
                            </label>
                            <input type="password" id="confirm_password" name="confirm_password" class="form-control" 
                                placeholder="再次输入密码">
                        </div>

                        <div class="form-group">
                            <label class="form-label" for="email">
                                邮箱
                            </label>
                            <input type="email" id="email" name="email" class="form-control" 
                                placeholder="可选，用于密码找回" 
                                value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>">
                        </div>

                        <div class="inline-fields">
                            <div class="form-group">
                                <label class="form-label" for="is_admin">
                                    用户角色
                                </label>
                                <select id="is_admin" name="is_admin" class="form-control">
                                    <option value="0" <?php echo isset($_POST['is_admin']) && $_POST['is_admin'] == 0 ? 'selected' : ''; ?>>普通用户</option>
                                    <option value="1" <?php echo isset($_POST['is_admin']) && $_POST['is_admin'] == 1 ? 'selected' : ''; ?>>管理员</option>
                                </select>
                            </div>

                            <div class="form-group">
                                <label class="form-label" for="status">
                                    账号状态
                                </label>
                                <select id="status" name="status" class="form-control">
                                    <option value="1" <?php echo isset($_POST['status']) && $_POST['status'] == 1 ? 'selected' : ''; ?>>正常</option>
                                    <option value="0" <?php echo isset($_POST['status']) && $_POST['status'] == 0 ? 'selected' : ''; ?>>禁用</option>
                                </select>
                            </div>
                        </div>

                        <div class="form-actions">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i>创建用户
                            </button>
                            <button type="reset" class="btn btn-outline">
                                <i class="fas fa-redo"></i>重置
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </main>
    </div>
</body>
</html>